<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="file" name="" id="file1">
    <button id="btnupload">上传文件</button>
    <br />
    <img src="" alt="" id="img" width="800">

    <script>
        var btnupload = document.querySelector('#btnupload');
        //2.为按钮绑定单击事件
        btnupload.addEventListener('click', function () {
            //3.获取到用户选择的文件列表
            var files = document.querySelector('#file1').files;
            if (files.length <= 0) {
                return alert('请选择要上传的文件');
            }
            var fd = new FormData();
            //将用户选择的文件添加到FormData
            fd.append('avatar', files[0]);


            //1.创建xhr对象
            var xhr = new XMLHttpRequest();
            //2.调用open函数
            xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar');
            //3.发起请求
            xhr.send(fd);

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);
                    if (data.status === 200) {
                        document.querySelector('#img').src = 'http://www.liulongbin.top:3006' + data.url;
                    } else {
                        console.log('失败');
                    }
                }
            }
        })
    </script>
</body>

</html>